package patrol.mobile.com.mobilepatrol.activity.bridge.regular;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.realm.Realm;
import io.realm.RealmResults;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjqsb;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjqstpb;
import patrol.mobile.com.mobilepatrol.bean.Qldqjcb;
import patrol.mobile.com.mobilepatrol.manager.QManager;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

import static patrol.mobile.com.mobilepatrol.PatrolApp.realm;
import static patrol.mobile.com.mobilepatrol.R.id.et;
import static patrol.mobile.com.mobilepatrol.R.id.tv;

/**
 * Created by apple on 17/10/5.
 */

public class BridgeRegularCheckBrokenDetailActivity extends BaseActivity {
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    @BindView(R.id.item1)
    RelativeLayout rl1;

    @BindView(R.id.item2)
    RelativeLayout rl2;

    @BindView(R.id.item3)
    RelativeLayout rl3;

    private EditText et2;
    private EditText et3;

    @BindView(R.id.bt)
    Button bt;

    @BindView(R.id.iv_pic)
    ImageView iv_pic;

    @BindView(R.id.rl_pic)
    RelativeLayout rl_pic;
    //一个桥梁定期检查
    private String qldqjcid;
    //一个桥梁
    private String qlcode;
    private Qldqjcb bridgeDQ;
    String mId;
    private String mtpbm = "";

    /** popup窗口里的ListView */
    private ListView mTypeLv;
    /** popup窗口 */
    private PopupWindow typeSelectPopup;

    /** 模拟的假数据 */
    private List<String> bjndata;

    /** 数据适配器 */
    private ArrayAdapter<String> dataAdapter;
    private TextView tv_bj;
    private String[] bbjc;
    private String bjcode="";
    private String bjname="";
    //    private List<QldqjcBjqsb> mList = new ArrayList<>();
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_regular_check_detail;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
//        initImagePicker();
    }

    @Override
    public void initView() {
        super.initView();
        initImagePicker();

        TextView tv1 = rl1.findViewById(tv);
        tv1.setText("部件");
        tv_bj = rl1.findViewById(R.id.tv1);

        TextView tv2 = rl2.findViewById(tv);
        tv2.setText("缺损位置");
        et2 = rl2.findViewById(et);

        TextView tv3 = rl3.findViewById(tv);
        tv3.setText("缺损状况");
        et3 = rl3.findViewById(et);
    }

    @Override
    public void initData() {
        super.initData();
        qldqjcid = getIntent().getStringExtra("qldqjcid");
        qlcode = getIntent().getStringExtra("qlcode");
        mId = getIntent().getStringExtra("id");
        bridgeDQ = QManager.getBridgeDQ(qlcode, qldqjcid);
//        mList = bridgeDQ.bjqs;
        if (mId != null && !mId.equals("")) {
            QldqjcBjqsb bjqs = QManager.getBridgebjqs(mId);
            RealmResults<QldqjcBjqstpb> tps = PatrolApp.realm.where(QldqjcBjqstpb.class).equalTo("tpbm", bjqs.tpbm).findAll();
            if (tps != null && tps.size() > 0) {
                String tpbm = tps.get(0).tpbm;
                String cfdz = tps.get(0).cfdz;
                final String bdcfdz = tps.get(0).bdcfdz;
                if (cfdz!=null&&!cfdz.equals("")){
                    PatrolApp.displayRoundImage(iv_pic, "http://211.101.37.245:8001" + cfdz, new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String imageUri, View view) {
                            Log.d("shj--","onLoadingStarted");
                        }

                        @Override
                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                            if (!bdcfdz.equals("")){
                                PatrolApp.displayRoundImage(iv_pic,"file://"+bdcfdz);
                            }
                        }

                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            Log.d("shj--","onLoadingComplete");
                        }

                        @Override
                        public void onLoadingCancelled(String imageUri, View view) {
                            Log.d("shj--","onLoadingCancelled");
                        }
                    });
                }else{
                    if (!bdcfdz.equals("")){
                        PatrolApp.displayRoundImage(iv_pic,"file://"+bdcfdz);
                    }
                }
            }

            bjcode = bjqs.bj;
            bjname = bjqs.bjname;
            tv_bj.setText(bjqs.bjname);
            et2.setText(bjqs.qswz);
            et3.setText(bjqs.qszk);
        }

    }

    @Override
    public void setListener() {
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String wz = et2.getText().toString().trim();
                final String zk = et3.getText().toString().trim();
                if (bjcode.equals("")) {
                    showToast("请填写部件");
                    return;
                }
                if (wz.equals("")) {
                    showToast("请填写缺损位置");
                    return;
                }
                if (zk.equals("")) {
                    showToast("请填写缺损状况");
                    return;
                }

                //一个部件缺损id，修改操作
                if (mId != null && !mId.equals("")) {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            //根据id拿到对象修改
                            RealmResults<QldqjcBjqsb> br = realm.where(QldqjcBjqsb.class).equalTo("id", mId).findAll();
                            QldqjcBjqsb qldqjcBjqsb = br.get(0);
                            qldqjcBjqsb.qszk = zk;
                            qldqjcBjqsb.qswz = wz;
                            qldqjcBjqsb.bj = bjcode;
                            qldqjcBjqsb.bjname = bjname;
                            qldqjcBjqsb.isUp = false;
                            mtpbm = qldqjcBjqsb.tpbm;
                            //有图片
                            if (images != null) {
                                String name = images.get(0).name;
                                //根据tpbm拿到图片，目前一个部件缺损有一张图片
                                RealmResults<QldqjcBjqstpb> tps = realm.where(QldqjcBjqstpb.class).equalTo("tpbm", mtpbm).findAll();
                                //有图片，修改
                                if (tps != null && tps.size() > 0) {
                                    tps.get(0).bdcfdz = images.get(0).path;

                                    tps.get(0).fjmc = mtpbm+name.substring(name.lastIndexOf("."));
                                    tps.get(0).isUp = false;
                                    //没有图片就增加图片
                                } else {
                                    QldqjcBjqstpb tp = realm.createObject(QldqjcBjqstpb.class);
                                    tp.id = CommonUtil.getUUID();
                                    tp.qldqjcid = qldqjcid;
                                    tp.tpbm = CommonUtil.getUUID();
                                    tp.bdcfdz = images.get(0).path;
                                    tp.fjmc = tp.tpbm+name.substring(name.lastIndexOf("."));
                                    tp.isUp = false;
                                    bridgeDQ.bjqstp.add(tp);
                                    qldqjcBjqsb.tpbm = tp.tpbm;
                                    mtpbm = tp.tpbm;

                                }
                            }
                        }
                    });
                } else {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            //一个部件缺损对象
                            QldqjcBjqsb qldqjcBjqsb = realm.createObject(QldqjcBjqsb.class);
                            qldqjcBjqsb.qldqjcid = qldqjcid;
                            qldqjcBjqsb.id = CommonUtil.getUUID();
                            mId = qldqjcBjqsb.id;
                            qldqjcBjqsb.qszk = zk;
                            qldqjcBjqsb.qswz = wz;
                            qldqjcBjqsb.bj = bjcode;
                            qldqjcBjqsb.bjname = bjname;
                            qldqjcBjqsb.isUp = false;


                            if (images != null) {
                                QldqjcBjqstpb tp = realm.createObject(QldqjcBjqstpb.class);
                                tp.isUp = false;
                                tp.id = CommonUtil.getUUID();
                                tp.qldqjcid = qldqjcid;
                                tp.tpbm = CommonUtil.getUUID();
                                tp.bdcfdz = images.get(0).path;
                                String name = images.get(0).name;

                                tp.fjmc = tp.tpbm+name.substring(name.lastIndexOf("."));
                                //定期检查列表有一个图片列表
                                bridgeDQ.bjqstp.add(tp);
                                //部件缺损对象根据图片编码拿到自己在列表中的图片
                                qldqjcBjqsb.tpbm = tp.tpbm;
                                bridgeDQ.bjqs.add(qldqjcBjqsb);
                                mtpbm = tp.tpbm;
                            } else {
                                bridgeDQ.bjqs.add(qldqjcBjqsb);
                                mtpbm = qldqjcBjqsb.tpbm;
                            }
                        }
                    });
                }
//                if (images != null && images.size() > 0) {
//                    uploadFile(images.get(0).path);
//                } else {
                    QManager.setBridegDQUpState(qldqjcid,false);
                    QManager.setQLUpState(qlcode,false);
                    Intent mIntent = new Intent();
                    // 设置结果，并进行传送
                    setResult(200, mIntent);
                    CommonUtil.exitActivityAndBackAnim(BridgeRegularCheckBrokenDetailActivity.this, true);
//                }

            }
        });
        rl_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                ImagePicker.getInstance().setSelectLimit(1);
                                Intent intent = new Intent(BridgeRegularCheckBrokenDetailActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                ImagePicker.getInstance().setSelectLimit(1);
                                Intent intent1 = new Intent(BridgeRegularCheckBrokenDetailActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
            }
        });
        rl1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 点击控件后显示popup窗口
                initSelectPopup();
                // 使用isShowing()检查popup窗口是否在显示状态
                if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
                    typeSelectPopup.showAsDropDown(tv_bj, 0, 10);
                }
            }
        });
    }
    /**
     * 初始化popup窗口
     */
    private void initSelectPopup() {
        mTypeLv = new ListView(this);
        bjData();
        // 设置适配器
        dataAdapter = new ArrayAdapter<String>(this, R.layout.popup_text_item, bjndata);
        mTypeLv.setAdapter(dataAdapter);

        // 设置ListView点击事件监听
        mTypeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 在这里获取item数据
                bjname = bjndata.get(position);
                // 把选择的数据展示对应的TextView上
                tv_bj.setText(bjname);
                bjcode = bbjc[position];
                // 选择完后关闭popup窗口
                typeSelectPopup.dismiss();
            }
        });
        typeSelectPopup = new PopupWindow(mTypeLv, tv_bj.getWidth(), ActionBar.LayoutParams.WRAP_CONTENT, true);
        // 取得popup窗口的背景图片
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg1);
        typeSelectPopup.setBackgroundDrawable(drawable);
        typeSelectPopup.setFocusable(true);
        typeSelectPopup.setOutsideTouchable(true);
        typeSelectPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 关闭popup窗口
                typeSelectPopup.dismiss();
            }
        });
    }

    private void bjData() {
        Resources resources = getResources();
        bbjc = resources.getStringArray(R.array.bbjc);
        String[] bbjn = resources.getStringArray(R.array.bbjn);
        bjndata = new ArrayList<>();
        for (int i=0;i<bbjc.length;i++){
            bjndata.add(bbjn[i]);
        }

    }
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);//允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setFocusWidth(600);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(600);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
        imagePicker.setMultiMode(false);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
    }


    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    PatrolApp.displayRoundImage(iv_pic, "file://" + images.get(0).path);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    PatrolApp.displayRoundImage(iv_pic, "file://" + images.get(0).path);
                }
            }
        }
    }

    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CommonUtil.exitActivityAndBackAnim(BridgeRegularCheckBrokenDetailActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("桥梁定期检查缺损详情");
    }

//    public void uploadFile(String path) {
//        String imgname;
//        File file = new File(path);
//        if (!file.exists()) {
//            Toast.makeText(BridgeRegularCheckBrokenDetailActivity.this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        //根据tpbm拿到图片，目前一个部件缺损有一张图片
//        RealmResults<QldqjcBjqstpb> tps = realm.where(QldqjcBjqstpb.class).equalTo("tpbm", mtpbm).findAll();
//        //修改图片名称
//        if (tps != null && tps.size() > 0 && !tps.get(0).fjmc.equals("")) {
//            imgname = tps.get(0).fjmc;
//        } else {
//            imgname = file.getName();
//        }
//        Map<String, String> params = new HashMap<>();
//        params.put("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username);
//        params.put("passWord", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
////        Logger.d(images);
//        Logger.d(file.getName());
//        OkHttpUtils.post()//
//                .addFile("upfile", imgname, file)//
//                .url(SPUtils.get(Constants.current_ser, "") + Urls.uploadTp)//
//                .params(params)//
////                .headers(headers)//
//                .build()//
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        showToast("图片上传失败");
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        try {
//                            JSONObject obj = new JSONObject(response);
//                            int state = obj.optInt("state");
//                            final String imgname = obj.getString("fileName");
//                            if (state == 200) {
//
//                                realm.executeTransaction(new Realm.Transaction() {
//
//                                    @Override
//                                    public void execute(Realm realm) {
//                                        //根据tpbm拿到图片，目前一个部件缺损有一张图片
//                                        RealmResults<QldqjcBjqstpb> tps = realm.where(QldqjcBjqstpb.class).equalTo("tpbm", mtpbm).findAll();
//                                        //修改图片名称
//                                        if (tps != null && tps.size() > 0) {
//                                            tps.get(0).fjmc = imgname;
//                                        }
//                                    }
//                                });
//                                QManager.setBridegDQUpState(qldqjcid,false);
//                                QManager.setQLUpState(qlcode,false);
//                                showToast("图片上传成功");
//                                Intent mIntent = new Intent();
//                                // 设置结果，并进行传送
//                                setResult(200, mIntent);
//                                CommonUtil.exitActivityAndBackAnim(BridgeRegularCheckBrokenDetailActivity.this, true);
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//
//                    }
//                });
//    }
}
